package com.iplant.pdm.controller.fpc;

import com.iplant.base.po.Pagination;
import com.iplant.base.po.ServiceResult;
import com.iplant.base.po.excel.ExcelData;
import com.iplant.base.utils.RetCode;
import com.iplant.base.utils.excel.ExcelReader;
import com.iplant.base.utils.serializer.CloneTool;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.orm.ORMUtils;
import com.iplant.base.utils.sql.orm.PoService;
import com.iplant.basic.controller.BasicController;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.pdm.service.FPCService;
import com.iplant.pdm.service.po.bop.FPCRoute;
import com.iplant.pdm.service.po.fpc.flow.FPCFlowPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/FPCRoute")
public class FPCRouteController extends BasicController<FPCRoute> {
    private static final Logger logger = LoggerFactory.getLogger(FPCRouteController.class);

    PoService<FPCRoute> mPoService = ORMUtils.GetPoService(FPCRoute.class);

    @Autowired
    FPCService mFPCService;

    public FPCRouteController() {
        super(FPCRoute.class);
    }

    @PostMapping("/SetCurrent")
    public Object SetCurrent(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Object wResult = new Object();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            if (!wParam.containsKey("data") || !wParam.containsKey("IsStandard")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }

            int wIsStandard = StringUtils.parseInt(wParam.get("IsStandard"));
            FPCRoute wRoute = CloneTool.Clone(wParam.get("data"), FPCRoute.class);

            ServiceResult<Integer> wServiceResult = mFPCService.FPC_RouteSetCurrent(wBMSEmployee, wRoute, wIsStandard);

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "");
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 查询待竣工确认过滤项
     */
    @GetMapping("/All")
    public Object All(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            Map<String, Object> wParams = GetParamsMap(request);
            Pagination wPagination = GetPagination(request);

            ServiceResult<List<FPCRoute>> wServiceResult = mFPCService.FPC_QueryRouteAll(wLoginUser, wParams,
                    wPagination);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, wPagination.getTotalPage());
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 查询流程图数据
     */
    @GetMapping("/FlowDataPart")
    public Object FlowDataPart(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            int wRouteID = StringUtils.parseInt(request.getParameter("RouteID"));
            int wRoutePartID = StringUtils.parseInt(request.getParameter("RoutePartID"));

            if (wRouteID <= 0 && wRoutePartID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<List<FPCFlowPart>> wServiceResult = mFPCService.FPC_QueryFlowDataPart(wLoginUser, wRouteID,
                    wRoutePartID);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
                for (String wKey : wServiceResult.CustomResult.keySet()) {
                    SetResult(wResult, wKey, wServiceResult.CustomResult.get(wKey));
                }
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 激活或禁用
     */
    @Override
    @PostMapping("/Active")
    public Object Active(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            if (!wParam.containsKey("Active") || !wParam.containsKey("data")) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            int wActive = StringUtils.parseInt(wParam.get("Active"));
            List<FPCRoute> wFPCRouteList = CloneTool.CloneArray(wParam.get("data"),
                    FPCRoute.class);
            if (wFPCRouteList == null || wFPCRouteList.size() == 0 || wFPCRouteList.stream().anyMatch(p -> p.ID <= 0)) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = mFPCService.FPC_RouteActive(wLoginUser, wActive,
                    wFPCRouteList);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 工艺BOP复制
     */
    @GetMapping("/Copy")
    public Object Copy(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            int wRouteID = StringUtils.parseInt(request.getParameter("RouteID"));
            String wNewVersion = StringUtils.parseString(request.getParameter("NewVersion"));
            int wIsCopyParameters = StringUtils.parseInt(request.getParameter("IsCopyParameters"));
            int wBOPParentID = StringUtils.parseInt(request.getParameter("BOPParentID"));
            int wActive = StringUtils.parseInt(request.getParameter("Active"), 1);
            if (wRouteID <= 0 || StringUtils.isEmpty(wNewVersion)) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = mFPCService.FPC_RouteCopy(wLoginUser, wRouteID, wNewVersion,
                    wIsCopyParameters, wBOPParentID, wActive);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 导入
     */
    @PostMapping("/Import")
    public Object ImportOrder(HttpServletRequest request, @RequestParam("file") MultipartFile[] files) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            if (files.length == 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, "提示：没有要上传的Excel文件！");
            }

            ServiceResult<Integer> wServiceResult = new ServiceResult<>();
            ServiceResult<ExcelData> wExcelData = null;
            String wOriginalFileName = null;
            for (MultipartFile wMultipartFile : files) {
                wOriginalFileName = wMultipartFile.getOriginalFilename();

                assert wOriginalFileName != null;
                if (wOriginalFileName.contains("xlsx"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xlsx", 1000000);
                else if (wOriginalFileName.contains("xls"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xls", 1000000);

                assert wExcelData != null;
                if (StringUtils.isNotEmpty(wExcelData.FaultCode)) {
                    wResult = GetResult(RetCode.SERVER_CODE_ERR, wExcelData.FaultCode);
                    return wResult;
                }

                wServiceResult = mFPCService.FPC_ImportRoute(wLoginUser, wExcelData.Result);

                if (!StringUtils.isEmpty(wServiceResult.FaultCode))
                    break;
            }

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "导入成功!", null, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 导出
     */
    @GetMapping("/Export")
    public Object Export(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            int wRouteID = StringUtils.parseInt(request.getParameter("RouteID"));
            if (wRouteID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<String> wServiceResult = mFPCService.FPC_ExportRoute(wLoginUser, wRouteID);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 清理脏数据
     */
    @GetMapping("/CleanUpDirtyData")
    public Object CleanUpDirtyData(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            ServiceResult<Integer> wServiceResult = mFPCService.FPC_CleanUpDirtyData(wLoginUser);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }
}
